package com.yinhe.music.yhmusic.songmenu;


import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.support.design.widget.AppBarLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hwangjr.rxbus.RxBus;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.annotation.Tag;
import com.hwangjr.rxbus.thread.EventThread;
import com.yinhe.music.common.GlideHelper.GlideHelper;
import com.yinhe.music.event.RxBusEventType;
import com.yinhe.music.event.RxbusNullObject;
import com.yinhe.music.yhmusic.R;
import com.yinhe.music.yhmusic.base.BaseBarStateChangeListener;
import com.yinhe.music.yhmusic.base.BaseModel;
import com.yinhe.music.yhmusic.base.BasePresenter;
import com.yinhe.music.yhmusic.base.BaseServiceActivity;
import com.yinhe.music.yhmusic.comment.CommentListActivity;
import com.yinhe.music.yhmusic.constants.IConstants;
import com.yinhe.music.yhmusic.constants.KeyConstants;
import com.yinhe.music.yhmusic.model.Music;
import com.yinhe.music.yhmusic.model.SongMenuList;
import com.yinhe.music.yhmusic.music.list.MusicListFragment;
import com.yinhe.music.yhmusic.personal.UserInfoActivity;
import com.yinhe.music.yhmusic.personal.modify.ModifyActivity;
import com.yinhe.music.yhmusic.songmenu.contract.ISongMenuContract;
import com.yinhe.music.yhmusic.songmenu.presenter.SongMenuPresenter;
import com.yinhe.music.yhmusic.utils.Preferences;
import com.yinhe.music.yhmusic.widget.CommentView;

import butterknife.BindView;

/**
 * 歌单界面
 *
 * @author 何晓华
 */
public class SongMenuActivity extends BaseServiceActivity implements ISongMenuContract.ISongMenuView {
    @BindView(R.id.album_art)
    ImageView albumArt;
    @BindView(R.id.menu_pic)
    ImageView menuPic;
    @BindView(R.id.menu_title)
    TextView menuTitle;
    @BindView(R.id.author_pic)
    ImageView authorPic;
    @BindView(R.id.author_name)
    TextView authorName;
    @BindView(R.id.menu_collect)
    TextView menuCollect;
    @BindView(R.id.menu_down)
    TextView menuDown;
    @BindView(R.id.headerdetail)
    RelativeLayout headerDetail;
    @BindView(R.id.appbar)
    AppBarLayout appbar;
    @BindView(R.id.comment_view)
    CommentView commentIcon;
    @BindView(R.id.menu_comment)
    RelativeLayout menuComment;
    @BindView(R.id.arrow)
    ImageView arrow;
    @BindView(R.id.ll_user)
    LinearLayout userLayout;

    private Music.Type type;
    private int menuId;
    private SongMenuList mMenu;
    /**
     * 是否为我喜欢的歌单
     */
    private boolean isLike;
    private int hasCollect;
    private boolean editable;

    int collectNum;


    private boolean loadImage;

    ActionBar actionBar;
    private SongMenuPresenter mPresenter;

    @Override
    public void initView() {
        RxBus.get().register(this);
        //toolbar
        hideToolbar();
        setTransparentToolbar("歌单");
        actionBar = getSupportActionBar();

        showQuickControl(true);

        getMenuInfo();
        mPresenter.getSongMenuInfo(menuId);
    }

    @Override
    protected void onDestroy() {
        RxBus.get().unregister(this);
        super.onDestroy();
    }

    @Override
    public int getLayoutResId() {
        return R.layout.activity_menu_playlist;
    }

    @Override
    public BasePresenter getPresenter() {
        return mPresenter;
    }

    @Override
    public void initPresenter() {
        mPresenter = new SongMenuPresenter();
        mPresenter.attachModelView(new BaseModel(), this);
    }

    /**
     * 获取传入的MenuInfo部分参数
     */
    private void getMenuInfo() {
        if (getIntent() != null) {
            mMenu = (SongMenuList) getIntent().getSerializableExtra("menu");
            type = (Music.Type) getIntent().getSerializableExtra("type");
            menuId = getIntent().getIntExtra("menuid", 0);
            editable = getIntent().getBooleanExtra("editable", false);
            isLike = getIntent().getBooleanExtra("like", false);

            if (mMenu != null) {
                initHeadView(mMenu);
            }
        }
    }

    private void setMusicList() {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction tx = fm.beginTransaction();
        tx.add(R.id.FrameLayout, MusicListFragment.newInstance(IConstants.SONGMENU_MUSIC_LIST, menuId, type, mMenu.getSongNum()));
        tx.commitAllowingStateLoss();
    }

    /**
     * 按钮监听事件
     */
    private void setListener() {
        userLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mMenu != null && mMenu.getUserInfo() != null) {
                    Intent intent = new Intent(SongMenuActivity.this, UserInfoActivity.class);
                    intent.putExtra(KeyConstants.KEY_USER_ID, mMenu.getUserInfo().getUserId());
                    startActivity(intent);
                }
            }
        });
        if (type == Music.Type.LOCAL && isLike) {
            menuCollect.setAlpha((float) 0.3);
            menuComment.setAlpha((float) 0.3);
        } else {
            menuComment.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startCommentView();
                }
            });
            menuCollect.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    collectMenu();
                }
            });
        }
        menuDown.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RxBus.get().post(RxBusEventType.SongMenu.DOWNLOAD_MENU, RxbusNullObject.INSTANCE);
            }
        });

    }

    /**
     * 设置头部
     */
    private void initHeadView(SongMenuList mMenu) {
        if (loadImage) {
            return;
        }

        menuTitle.setText(mMenu.getSongMenuName());

        appbar.addOnOffsetChangedListener(new BaseBarStateChangeListener() {

            @Override
            public void onOffSetChanged(AppBarLayout appBarLayout, int i) {
                actionBar.setBackgroundDrawable(null);
                float a = (float) Math.abs(i) / (appBarLayout.getTotalScrollRange());
                headerDetail.setAlpha(1f - a);
            }

            @Override
            public void onStateChanged(AppBarLayout appBarLayout, State state) {
                if (state == State.EXPANDED) {
                    setTitle("歌单");
                } else if (state == State.COLLAPSED) {
                    if (mMenu.getSongMenuName() != null) {
                        setTitle(mMenu.getSongMenuName());
                    }
                } else {
                    setTitle("歌单");
                }
            }
        });

        setPlaylistArt(mMenu.getImage());
        loadImage = true;
    }

    @Override
    public void setSongMenuUI(SongMenuList menuInfo) {
        mMenu = menuInfo;
        setListener();
        collectNum = menuInfo.getCollectNum();
        menuCollect.setText(String.valueOf(collectNum));
        commentIcon.setUnreadCount(menuInfo.getCommentNum());
        authorName.setText(menuInfo.getUserInfo().getNickname());
        hasCollect = menuInfo.getCollectStatus();
        setMusicList();
        initHeadView(menuInfo);
        GlideHelper.setCircleImageResource(authorPic, menuInfo.getUserInfo().getImage(), R.drawable.default_user_head);
        setIsCollect();
    }

    /**
     * 设置收藏状态
     */
    private void setIsCollect() {
        if (hasCollect == 1) {
            Drawable top = getResources().getDrawable(R.drawable.ic_favourite_added);
            top.setBounds(0, 0, top.getIntrinsicWidth(), top.getIntrinsicHeight());
            menuCollect.setCompoundDrawables(null, top, null, null);
        } else {
            Drawable top = getResources().getDrawable(R.drawable.ic_favourite_white);
            top.setBounds(0, 0, top.getIntrinsicWidth(), top.getIntrinsicHeight());
            menuCollect.setCompoundDrawables(null, top, null, null);
        }
    }

    /**
     * 加载歌单封面
     */
    private void setPlaylistArt(String image) {
        if (isLike && image.isEmpty()) {
            GlideHelper.setBlurImageResource(albumArt, R.drawable.ic_my_fav, 25f, 0x99FFFFFF);
            GlideHelper.setImageResource(menuPic, R.drawable.ic_my_fav);
        } else {
            GlideHelper.setImageResource(menuPic, image, R.drawable.default_cover);
            GlideHelper.setBlurImageResource(albumArt, image, 25f, 0x99FFFFFF);
        }
    }

    /**
     * 右上更多菜单
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        if (editable && type == Music.Type.LOCAL) {
            inflater.inflate(R.menu.menu_play_list, menu);
        }
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        super.onOptionsItemSelected(item);
        if (item.getItemId() == R.id.navigation_item_edit) {
            Intent intent = new Intent(this, ModifyActivity.class);
            intent.putExtra(KeyConstants.KEY_MODIFY_ID, String.valueOf(menuId));
            intent.putExtra(KeyConstants.KEY_IMAGE, mMenu.getImage());
            intent.putExtra(KeyConstants.KEY_NAME, mMenu.getSongMenuName());
            intent.putExtra(KeyConstants.KEY_MODIFY_TYPE, IConstants.MODIFY_SONGMENU_INFO);
            startActivity(intent);
        }
        return true;
    }

    /**
     * 收藏歌单
     */
    private void collectMenu() {
        if (Preferences.getLoginSn().isEmpty()) {
            startLogin();
        } else {
            mPresenter.batchCollection(menuId, hasCollect);
        }
    }

    /**
     * 跳转评论
     */
    private void startCommentView() {
        Intent it = new Intent(this, CommentListActivity.class);
        it.putExtra("name", mMenu.getSongMenuName());
        it.putExtra("artist", mMenu.getUserInfo().getNickname());
        it.putExtra("cover", mMenu.getImage());
        it.putExtra("id", mMenu.getSongMenuId());
        it.putExtra("commentType", IConstants.SONGMENU);
        startActivity(it);
    }

    @Override
    public void updateCollectUI(int hasCollect) {
        this.hasCollect = hasCollect;
        if (hasCollect == 1) {
            collectNum++;
            menuCollect.setText(String.valueOf(collectNum));
        } else {
            collectNum--;
            menuCollect.setText(String.valueOf(collectNum));
        }
        setIsCollect();
    }

    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = {@Tag(RxBusEventType.SongMenu.UPDATE_MENU_NAME),
                    @Tag(RxBusEventType.SongMenu.UPDATE_MENU_IMAGE)}
    )
    public void onRxbusUpdateMenu(RxbusNullObject rxbusNullObject) {
        loadImage = false;
        mPresenter.getSongMenuInfo(menuId);
    }
}
